typora-copy-images-to: img

数组工具类

示例:

  1. public class ArrayTool{
  2. //该类中的方法都是静态的,所以该类是不需要创造对象的
  3. //为了保证不让他人创建该类对象,可以将构造函数私有化
  4. private ArrayTool(){}
  5. //获取整型数组的最大值
  6. public static int getMax(int[] arr){
  7. int maxIndex = 0;
  8. for(int x = 1; x < arr.length; x++){
  9. if(arr[x] > arr[maxIndex])
  10. maxIndex = x;
  11. }
  12. return arr[maxIndex];
  13. }
  14. //对数组进行选择排序
  15. public static void selectSort(int[] arr){
  16. for(int x = 0; x <arr.length -1; x++){
  17. for(int y = x + 1; y < arr.length; y++){
  18. if(arr[x] > arr[y])
  19. swap(arr,x,y);
  20. }
  21. }
  22. }
  23. //用于给数组进行元素的位置置换。
  24. private static void swap(int[] arr, int a,int b){
  25. int temp = arr[a];
  26. arr[a] = arr[b];
  27. arr[b] = temp;
  28. }
  29. //获取指定的元素在指定数组中的索引
  30. public static int getIndex(int[] arr, int key){
  31. for(int x = 0; x < arr.length; x++){
  32. if(arr[x] == key)
  33. return x;
  34. }
  35. return -1;
  36. }
  37. //将int 数组转换成字符串,格式是:[e1,e2,...]
  38. public static String arrayToString(int[] arr){
  39. String str = "[";
  40. for(int x = 0; x < arr.length; x++){
  41. if(x != arr.length - 1)
  42. str = str + arr[x] + ",";
  43. else
  44. str = str + arr[x] + "]";
  45. }
  46. return str;
  47. }
  48. }
  49. class ArrayToolDemo{
  50. //保证程序的独立运行
  51. public static void main(String[] args){
  52. int[] arr = {4,8,2,9,7,72,6};
  53. int max = ArrayTool.getMax(arr);
  54. System.out.println("max = " + max);
  55. int index = ArrayTool.getIndex(arr,10);
  56. System.out.println("index = " + index);
  57. }
  58. }

运行结果:

1491283464087